package org.goodsl.deploymap

/**
 * Created with IntelliJ IDEA.
 * User: Simon Xiao
 * Date: 12-12-19
 * Time: 上午9:59
 * Copyright goodsl.org 2012~2020
 */
class Env extends SysElement{
    ArrayList<Host> hosts = new ArrayList<Host>();

    HashMap<Service,List<DeployedService>> envServices = new HashMap<Service,List<DeployedService>>()

    Host getHost(String hostName){
        return  hosts.get(hostName)
    }

    List<DeployServiceRelation> serviceRelations = new ArrayList<DeployServiceRelation>()

    public Collection<Service> getServiceSet(){
        return envServices.keySet()
    }

    /**
     * delegate host{} int env{}
     * @param hostName
     * @param cl
     */
    void host(String hostName,Closure cl) {
        Host newHost = new  Host(name: hostName,system:this.system,env: this)
        this.hosts.add(newHost)


        cl.delegate = newHost
        cl.resolveStrategy = Closure.DELEGATE_FIRST
        cl()
    }


    /**
     * 建立已部署服务之间的通讯关系
     */
    public void buildServiceRelation(){

        //envServices.clear()
        //system.services.values().each {
        //    envServices.put(it,new ArrayList<DeployedService>() )
        //}

        hosts.each {Host host ->
            host.hostService.each { DeployedService depService ->
                List<DeployedService> depList = envServices.get(depService.service)
                if (depList == null){
                    depList = new ArrayList<DeployedService>()
                    envServices.put(depService.service,depList)
                }
                depList.add(depService)
            }
        }

        envServices.values().each {List<DeployedService> depList ->
            depList.each {DeployedService depService ->
                depService.service.relations.each {ServiceRelation relation ->

                    List<DeployedService> depListB = envServices.get(relation.serviceB)

                    if (depListB!=null && depListB.size()>0){
                        depListB.each {DeployedService depServiceB ->
                            DeployServiceRelation depRelation = new DeployServiceRelation(
                                    deployNameA: depService.deployName,
                                    deployNameB: depServiceB.deployName,
                                    relationType: relation.relationType,
                                    desc: relation.desc
                            )
                            serviceRelations.add(depRelation)
                        }
                    }
                }
            }
        }
    }

}

class DeployServiceRelation{
    String deployNameA
    String deployNameB
    ServiceRelationType relationType
    String desc
}
